﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Input;

namespace WcfClientGenerator.UI.Command
{
    public class DelegatingCommand : ICommand
    {
        #region Instance Fields (Private)

        readonly Action action;
        readonly Func<bool> canExecute;

        #endregion

        #region Instance Events (Public)

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (this.canExecute != null)
                    CommandManager.RequerySuggested += value;
            }
            remove
            {
                if (this.canExecute != null)
                    CommandManager.RequerySuggested -= value;
            }
        }

        #endregion

        #region Instance Constructors (Public)

        /// <summary>
        /// Creates a new command that can always execute.
        /// </summary>
        /// <param name="action">The execution logic.</param>
        public DelegatingCommand(Action action)
            : this(action, null)
        {
        }

        /// <summary>
        /// Creates a new command.
        /// </summary>
        /// <param name="action">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        public DelegatingCommand(Action action, Func<bool> canExecute)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            this.action = action;
            this.canExecute = canExecute;
        }

        #endregion

        #region Instance Methods (Public)

        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return this.canExecute == null ? true : this.canExecute();
        }

        public void Execute(object parameter)
        {
            this.action();
        }

        #endregion
    }
}
